<?php
namespace App\Service;

use App\Entity\Task;
use App\Repository\ConfigRepository;
use App\Repository\ShopTagRepository;
use Doctrine\Bundle\DoctrineBundle\Repository\ServiceEntityRepository;
use Doctrine\Persistence\ManagerRegistry;
use function Doctrine\ORM\QueryBuilder;

class TaskService extends ServiceEntityRepository
{

    public $shopTagRepository;
    public $configRepository;

    public function __construct(
        ManagerRegistry $registry
        ,ShopTagRepository $shopTagRepository
        ,ConfigRepository $configRepository
    )
    {
        parent::__construct($registry, Task::class);
        $this->shopTagRepository = $shopTagRepository;
        $this->configRepository = $configRepository;
    }


    public function getPublicList($lat,$lon,$page,$limit = 10)
    {
        $config = $this->configRepository->getByK("SEARCH_DISTANCE");//处理距离数据
        $distanceArr = myExplodeNumbers($config);
        $qb = $this->createQueryBuilder("A");
        $qb->select("A");
        $qb->join("App:UserAddress","B","with","A.address = B");
        $qb->where("A.type = 1");//1=自己创建的订单，2=购买服务创建的订单

        //地理位置筛选
        $km = calcLatLonFromDistance($distanceArr[0]);
        $qb->where("B.lat < ".($lat + $km))
            ->andWhere("B.lat > ".($lat - $km))
            ->andWhere("B.lon < ".($lon + $km))
            ->andWhere("B.lon > ".($lon - $km));
        //地理位置排序
        $qb->addSelect("SQRT(($lat - B.lat)*($lat - B.lat) + ($lon  - B.lon)*($lon  - B.lon)) AS distance");
        $qb->orderBy("SQRT(($lat - B.lat)*($lat - B.lat) + ($lon  - B.lon)*($lon  - B.lon))","ASC");

        $qb->setMaxResults($limit);
        $qb->setFirstResult($page * $limit - $limit);
        $data = $qb->getQuery()->execute();
    }

    public function dealWithTaskCreate(Task $task)
    {
        //1类目优先
        $cat1 = $task->getCat1();//todo 暂时先不匹配父栏目
        $cat2 = $task->getCat2();
        //---检查子栏目下数量过少再给到父栏目//todo 暂时先不这么设计了，只检查子栏目
        $qb = $this->_em->createQueryBuilder();
        $qb->from("App:Shop","Shop");
        $qb->innerJoin("Shop.categories","Cat","with","Cat = ".$cat2->getId());
        $qb->select("count(Shop.id) as num");


//        $qb->groupBy("Shop.id");
//        $qb->addGroupBy("Cat");
        //地理位置优先于区县设置
        $qb->where("Shop.city = '".$task->getAddress()->getCity()."'");

        //获取用户的地址区域

        $data = $qb->getQuery()->execute();
        $numCat1 = $data[0]["num"];
        var_dump($data);
    }
}